package com.financing.platform.task;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.platform.dao.IMessageDao;
import com.financing.platform.dao.IMessageMailDao;
import com.financing.platform.dao.IOrderDao;
import com.financing.platform.dao.IOrderManagerUserDao;
import com.financing.platform.dao.IOrderTmpDao;
import com.financing.platform.dto.MessageDTO;
import com.financing.platform.dto.MessageMailDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.service.IEmailTemplateService;
import com.financing.platform.util.DateUtil;
import com.financing.platform.util.Dict;
import com.financing.platform.util.StringUtil;
import com.financing.platform.vo.EmailTemplateUserVO;
import com.financing.platform.vo.OrderEmailVO;
import com.financing.platform.vo.OrderManagerUserVO;

/**
 * 
 * @ClassName: OrderPerMailJob
 * @Description: 用户订单预约通知订单管理部门 
 * @author  qiye
 * @date 2015年4月16日 下午1:19:29
 *
 */
@Component(value="orderPerMailJob" )
public class OrderPerMailJob {
	
	Logger log = Logger.getLogger(this.getClass());
	
	@Value("#{settings['orderPerWorkerList']}")
	private String orderPerWorkers;
	
	@Value("#{settings['orderManagerGroup']}")
	private String orderManagerGroup;
	
	@Autowired
	private IMessageMailDao messageMailDaoImpl;
	
	@Autowired
	private IOrderDao orderDaoImpl;
	
	@Autowired
	private IOrderManagerUserDao orderManagerUserDaoImpl;
	
	@Autowired
	private IEmailTemplateService emailTemplateServiceImpl;
	
	@Resource
	private MailSenderService mailSenderService;
	
	@Autowired
	private IMessageDao messageDaoImpl;
	
	@Autowired
	private IOrderTmpDao orderTmpDaoImpl;
	
//	@Scheduled(cron = "0 0 06 * * ?") 
//	@Scheduled(cron = "0 0/5 * * * ?") 
	public void orderPerMail(){
		try {
			List<EmailTemplateUserVO> list = orderDaoImpl.queryFaOrderPerForEmail();
			if(list!=null && list.size()>0){
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("time", DateUtil.getPerDay());
				param.put("count", list.size());
				param.put("list", list);
				param = emailTemplateServiceImpl.spliceEmailContent(Dict.mail_template_order_per, param);
				SendOrderMail(param,orderPerWorkers);
			}else{
				MailContentDTO mail = new MailContentDTO();
				mail.setRecAddress("chenming@superfa.cn");
				mail.setSubject("生产订单通知");
				mail.setContext("昨天没有订单！");
				mailSenderService.send(mail);
			}
		} catch (SQLException e) {
			log.error("order Mail error ",e);
			SendExceptionMail(e);
		}
	}
	
//	@Scheduled(cron = "0 0 06 *  * ?") 
//	@Scheduled(cron = "0 0/5 * * * ?") 
		public void orderPerTmpMail(){
		try {
			List<EmailTemplateUserVO> list = orderTmpDaoImpl.queryFaOrderPerTmpForEmail();
			if(list!=null && list.size()>0){
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("time", DateUtil.getPerDay());
				param.put("count", list.size());
				param.put("list", list);
				param = emailTemplateServiceImpl.spliceEmailContent(Dict.mail_template_order_per, param);
				SendOrderMail(param, orderPerWorkers);
			}else{
				MailContentDTO mail = new MailContentDTO();
				mail.setRecAddress("chenming@superfa.cn");
				mail.setSubject("生产订单通知");
				mail.setContext("昨天没有订单！");
				mailSenderService.send(mail);
			}
		} catch (SQLException e) {
			log.error("order  Mail error ",e);
			SendExceptionMail(e);
		}
	}
	
	//订单状态通知后台管理员
	@Scheduled(cron = "0 0 08 * * ?") 
//	@Scheduled(cron = "0 0/5 * * * ?") 
	public void orderManagerGroup(){
	try {
		
		//信托、资管订单
		List<OrderEmailVO> list = orderDaoImpl.queryneedSendEmailToManager();
		
	    // 拼装邮件正文
		StringBuffer mailContent = new StringBuffer();
		
		BigDecimal sumAmount = new BigDecimal(0);
		int countOrder = 0;
		mailContent.append("<table border=\"2\"><tr><td>产品名称</td><td>订单数(笔)</td><td>订单总金额(万元)</td><td>订单跟进人</td></tr>");
		for(OrderEmailVO tmp : list){
			if(tmp.getManager() == null){
				tmp.setManager("无");
			}
			mailContent.append("<tr><td>"+tmp.getProjectName())
						.append("</td><td>")
						.append(tmp.getTotalOrder())
						.append("</td><td>")
						.append(tmp.getSumOrderAmount().longValue()/10000)
						.append("</td><td>")
						.append(tmp.getManager())
						.append("</td></tr>");
			sumAmount = sumAmount.add(tmp.getSumOrderAmount());
			countOrder = countOrder + tmp.getTotalOrder();
		}
		mailContent.append("</table>");

		mailContent.insert(0, "万元;<br/>");
		mailContent.insert(0, sumAmount.longValue()/10000);
		mailContent.insert(0, "条:共计金额");
		mailContent.insert(0, countOrder);
		mailContent.insert(0,"<B>信托资管产品</B><br/>当前的订单有");
		
		StringBuffer mailContentDetail = new StringBuffer();
		List<OrderEmailVO> orderUsers = orderDaoImpl.queryneedSendEmailToManagerUser();
		
		for(OrderEmailVO tmp : orderUsers){
			UserInfoDTO user =new UserInfoDTO();
			user.setUserId(tmp.getManagerId());
			List<OrderEmailVO> tmpList = orderDaoImpl.queryneedSendEmailToManagerUserDetail(user);
			
			mailContentDetail.append("<br/>订单跟进人")
							 .append(tmp.getManager())
							 .append("，共计订单")
							 .append(tmpList.size())
							 .append("条，金额")
							 .append("{orderTotalAmount}万元;");
			
			BigDecimal orderTotalAmount = new BigDecimal(0);
			
			mailContentDetail.append("<table border=\"2\"><tr><td>订单号</td><td>订单当前状态</td><td>当前状态停留天数</td></tr>");
			for(OrderEmailVO userOrderDetail : tmpList){
				mailContentDetail.append("<tr><td>")
								 .append(userOrderDetail.getO_code())
								 .append("</td><td>")
								 .append(userOrderDetail.getO_status())
								 .append("</td><td>")
								 .append(userOrderDetail.getDateDiffnow())
								 .append("</td></tr>");
				orderTotalAmount = orderTotalAmount.add(userOrderDetail.getSumOrderAmount());
			}
			mailContentDetail.append("</table>");
			mailContentDetail.replace(0, mailContentDetail.length(), mailContentDetail.toString().replace("{orderTotalAmount}", Integer.valueOf((orderTotalAmount.intValue())/10000).toString()));
		}
		
		//pevc 订单
		List<OrderEmailVO> pevcList = orderDaoImpl.queryPevcneedSendEmailToManager();
	    // 拼装邮件正文
		StringBuffer mailContentPEVC = new StringBuffer();
		
		BigDecimal sumAmountPEVC = new BigDecimal(0);
		int countOrderPEVC = 0;
		mailContentPEVC.append("<table border=\"2\"><tr><td>产品名称</td><td>订单数(笔)</td><td>订单总金额(万元)</td><td>订单跟进人</td></tr>");
		for(OrderEmailVO tmp : pevcList){
			if(tmp.getManager() == null){
				tmp.setManager("无");
			}
			if(tmp.getSumOrderAmount() == null){
				tmp.setSumOrderAmount(new BigDecimal(0));
			}
			mailContentPEVC.append("<tr><td>"+tmp.getProjectName())
						.append("</td><td>")
						.append(tmp.getTotalOrder())
						.append("</td><td>")
						.append(tmp.getSumOrderAmount().longValue()/10000)
						.append("</td><td>")
						.append(tmp.getManager())
						.append("</td></tr>");
			sumAmountPEVC = sumAmountPEVC.add(tmp.getSumOrderAmount());
			countOrderPEVC = countOrderPEVC + tmp.getTotalOrder();
		}
		mailContentPEVC.append("</table>");
		mailContentPEVC.insert(0, "万元;<br/>");
		mailContentPEVC.insert(0, sumAmountPEVC.longValue()/10000);
		mailContentPEVC.insert(0, "条:共计金额");
		mailContentPEVC.insert(0, countOrderPEVC);
		mailContentPEVC.insert(0,"<br/><br/><B>PE/VC产品</B><br/>当前的订单有");
		StringBuffer mailContentPEVCDetail = new StringBuffer();
		List<OrderEmailVO> orderPEVCUsers = orderDaoImpl.queryPEVCneedSendEmailToManagerUser();
		
		for(OrderEmailVO tmp : orderPEVCUsers){
			List<OrderEmailVO> tmpList = orderDaoImpl.queryPevcneedSendEmailToManagerUserDetail(tmp.getManagerId());
			mailContentPEVCDetail.append("<br/>订单跟进人")
							 .append(tmp.getManager())
							 .append("，共计订单")
							 .append(tmpList.size())
							 .append("条，金额")
							 .append("{orderTotalAmount}万元;");
			BigDecimal orderTotalAmount = new BigDecimal(0);
			
			mailContentPEVCDetail.append("<table border=\"2\"><tr><td>订单号</td><td>订单当前状态</td><td>当前状态停留天数</td></tr>");
			for(OrderEmailVO userOrderDetail : tmpList){
				mailContentPEVCDetail.append("<tr><td>")
								 .append(userOrderDetail.getO_code())
								 .append("</td><td>")
								 .append(userOrderDetail.getO_status())
								 .append("</td><td>")
								 .append(userOrderDetail.getDateDiffnow())
								 .append("</td></tr>");
				orderTotalAmount = orderTotalAmount.add(userOrderDetail.getSumOrderAmount());
			}
			mailContentPEVCDetail.append("</table>");
			mailContentPEVCDetail.replace(0, mailContentDetail.length(), mailContentPEVCDetail.toString().replace("{orderTotalAmount}", Integer.valueOf((orderTotalAmount.intValue())/10000).toString()));
		}
		
		
		//私募订单
		List<OrderEmailVO> listSM = orderDaoImpl.queryneedSendEmailToManagerSM();
		
	    // 拼装邮件正文
		StringBuffer mailContentSM = new StringBuffer();
		
		BigDecimal sumAmountSM = new BigDecimal(0);
		int countOrderSM = 0;
		mailContentSM.append("<table border=\"2\"><tr><td>产品名称</td><td>订单数(笔)</td><td>订单总金额(万元)</td><td>订单跟进人</td></tr>");
		for(OrderEmailVO tmp : listSM){
			if(tmp.getManager() == null){
				tmp.setManager("无");
			}
			if(tmp.getSumOrderAmount() == null){
				tmp.setSumOrderAmount(new BigDecimal(0));
			}
			
			mailContentSM.append("<tr><td>"+tmp.getProjectName())
						.append("</td><td>")
						.append(tmp.getTotalOrder())
						.append("</td><td>")
						.append(tmp.getSumOrderAmount().longValue()/10000)
						.append("</td><td>")
						.append(tmp.getManager())
						.append("</td></tr>");
		
			sumAmountSM = sumAmountSM.add(tmp.getSumOrderAmount());
			countOrderSM = countOrderSM + tmp.getTotalOrder();
		}
		
		mailContentSM.append("</table>");

		mailContentSM.insert(0, "万元;<br/>");
		mailContentSM.insert(0, sumAmountSM.longValue()/10000);
		mailContentSM.insert(0, "条:共计金额");
		mailContentSM.insert(0, countOrderSM);
		mailContentSM.insert(0,"<br/><br/><B>私募产品</B><br/>当前的订单有");
		
		StringBuffer mailContentDetailSM = new StringBuffer();
		List<OrderEmailVO> orderUsersSM = orderDaoImpl.queryneedSendEmailToManagerUserSM();
		
		for(OrderEmailVO tmp : orderUsersSM){
			UserInfoDTO user =new UserInfoDTO();
			user.setUserId(tmp.getManagerId());
			List<OrderEmailVO> tmpListSM = orderDaoImpl.queryneedSendEmailToManagerUserDetailSM(user);
			
			mailContentDetailSM.append("订单跟进人")
							 .append(tmp.getManager())
							 .append("，共计订单")
							 .append(tmpListSM.size())
							 .append("条，金额")
							 .append("{orderTotalAmount}万元;");
			
			BigDecimal orderTotalAmount = new BigDecimal(0);
			
			mailContentDetailSM.append("<table border=\"2\"><tr><td>订单号</td><td>订单当前状态</td><td>当前状态停留天数</td></tr>");
			for(OrderEmailVO userOrderDetail : tmpListSM){
				mailContentDetailSM.append("<tr><td>")
								 .append(userOrderDetail.getO_code())
								 .append("</td><td>")
								 .append(userOrderDetail.getO_status())
								 .append("</td><td>")
								 .append(userOrderDetail.getDateDiffnow())
								 .append("</td></tr>");
				orderTotalAmount = orderTotalAmount.add(userOrderDetail.getSumOrderAmount());
			}
			mailContentDetailSM.append("</table>");
			mailContentDetailSM.replace(0, mailContentDetail.length(), mailContentDetailSM.toString().replace("{orderTotalAmount}", Long.valueOf(orderTotalAmount.intValue()/10000).toString()));
		}
		
			mailContent.append(mailContentDetail.toString())
			.append(mailContentPEVC).append(mailContentPEVCDetail)
						.append(mailContentSM)
						.append(mailContentDetailSM);
		
			Map<String,Object>  param = new HashMap<String,Object>();
			param.put(Dict.mail_content, mailContent.toString());
			param.put(Dict.mail_subject, "订单跟进状态");
			
			//发送邮件
			SendOrderMail(param,orderManagerGroup);
	} catch (SQLException e) {
		log.error("order  Mail error ",e);
		SendExceptionMail(e);
	}
}
	
	@Scheduled(cron = "0 0 08 * * ?") 
//	@Scheduled(cron = "0 0/5 * * * ?") 
	public void orderManager(){
		try{
			//查询所有的订单管理员
			List<OrderManagerUserVO> orderManagerUserList = orderManagerUserDaoImpl.queryOrderManagerUsers(null);
			
			for(OrderManagerUserVO tmp : orderManagerUserList){
				StringBuffer mailContentDetail = new StringBuffer();
				
				//如果用户邮箱为空则继续
				if(StringUtil.isNullOrEmptyStr(tmp.getEmail())){
					continue;
				}
				//查询每个订单管理员下面的非私募订单信息
				UserInfoDTO user =new UserInfoDTO();
				user.setUserId(tmp.getUserId());
				List<OrderEmailVO> tmpList = orderDaoImpl.queryneedSendEmailToManagerUserDetail(user);
				List<OrderEmailVO> pevcList = orderDaoImpl.queryPevcneedSendEmailToManagerUserDetail(tmp.getUserId());
				UserInfoDTO usertwo =new UserInfoDTO();
				usertwo.setUserId(tmp.getUserId());
				List<OrderEmailVO> tmpSMList = orderDaoImpl.queryneedSendEmailToManagerUserDetailSM(usertwo);
				
				if((tmpList.size() + tmpSMList.size()+pevcList.size()) == 0){
					mailContentDetail.append("您的订单为零，请加油!");
				}else{
					if(tmpList.size() != 0){
						mailContentDetail.append("<B>您的信托资管订单有：")
						 .append(tmpList.size())
						 .append("条。</B>");
						
						mailContentDetail.append("<table border=\"2\"><tr><td>产品名称</td><td>订单号</td><td>订单当前状态</td><td>当前状态停留天数</td></tr>");
						
						for(OrderEmailVO userOrderDetail : tmpList){
							mailContentDetail.append("<tr><td>")
												.append(userOrderDetail.getProjectName())
											 .append("</td><td>")
											 .append(userOrderDetail.getO_code())
											 .append("</td><td>")
											 .append(userOrderDetail.getO_status())
											 .append("</td><td>")
											 .append(userOrderDetail.getDateDiffnow())
											 .append("</td></tr>");
						}
						
						mailContentDetail.append("</table>");
						
					}
					
					if(pevcList.size() != 0){
						mailContentDetail.append("<B>您的PEVC订单有：")
						 .append(pevcList.size())
						 .append("条。</B>");
						
						mailContentDetail.append("<table border=\"2\"><tr><td>产品名称</td><td>订单号</td><td>订单当前状态</td><td>当前状态停留天数</td></tr>");
						
						for(OrderEmailVO userOrderDetail : pevcList){
							mailContentDetail.append("<tr><td>")
												.append(userOrderDetail.getProjectName())
											 .append("</td><td>")
											 .append(userOrderDetail.getO_code())
											 .append("</td><td>")
											 .append(userOrderDetail.getO_status())
											 .append("</td><td>")
											 .append(userOrderDetail.getDateDiffnow())
											 .append("</td></tr>");
						}
						
						mailContentDetail.append("</table>");
						
					}
					
					if(tmpSMList.size() != 0){
						//查询每个订单管理员下私募订单那信息
						mailContentDetail.append("<br><B>您的私募订单有：")
										 .append(tmpSMList.size())
										 .append("条。</B>");
						mailContentDetail.append("<table border=\"2\"><tr><td >产品名称</td><td>订单号</td><td>订单当前状态</td><td>当前状态停留天数</td></tr>");
						for(OrderEmailVO userOrderDetail : tmpSMList){
							mailContentDetail.append("<tr><td>")
											  .append(userOrderDetail.getProjectName())
											 .append("</td><td>")
											 .append(userOrderDetail.getO_code())
											 .append("</td><td>")
											 .append(userOrderDetail.getO_status())
											 .append("</td><td>")
											 .append(userOrderDetail.getDateDiffnow())
											 .append("</td></tr>");
						}
						mailContentDetail.append("</table>");
					}
				}
				
				Map<String,Object>  param = new HashMap<String,Object>();
				param.put(Dict.mail_content, mailContentDetail.toString());
				param.put(Dict.mail_subject, "订单状态跟进");
				SendOrderMail(param, tmp.getEmail());
			}
		} catch (SQLException e) {
			log.error("order  Mail error ",e);
			SendExceptionMail(e);
		}
	}
	
	/**
	 * 
	 * @Title: SendExceptionMail
	 * @Description: 发送异常邮件 
	 * @param @param e   
	 * @return void   
	 * @throws
	 */
	private void SendExceptionMail(Exception e){
		MailContentDTO mail = new MailContentDTO();
		try {
			InetAddress address = InetAddress.getLocalHost();
			mail.setSubject(address.getHostAddress()+"订单邮件异常通知");
		} catch (UnknownHostException e1) {
			mail.setSubject("订单邮件异常通知");
			log.warn("get localHost IP error!",e1);
		}
		mail.setRecAddress("chenming@superfa.cn");
		
		mail.setContext("订单邮件异常："+e.getMessage()+e);
		mailSenderService.send(mail);
	}

	/**
	 * 
	 * @Title: SendOrderMail
	 * @Description: 发送订单邮件 
	 * @param @param param
	 * @param @param emailAddress
	 * @param @throws SQLException   
	 * @return void   
	 * @throws
	 */
	private void SendOrderMail(Map<String,Object> param,String emailAddress) throws SQLException{
		if(!param.isEmpty() && param.size() >0){
			MessageDTO messageDTO = new MessageDTO();
			MessageMailDTO messageMailDTO = new MessageMailDTO();
			messageDTO.setMsgTitle((String)param.get(Dict.mail_subject));
			messageDTO.setMsgContent((String)param.get(Dict.mail_content));
			messageDTO.setMsgType(Dict.message_type_order);
			messageDTO.setStatus(Dict.status_normal);
			messageDTO.setCreateBy("system");
			messageDTO.setCreateDate(new Date());
			messageDTO.setUpdateBy("system");
			messageDTO.setUpdateDate(new Date());;
			messageMailDTO.setFpMailMessageId(messageDaoImpl.addMessage(messageDTO));
			messageMailDTO.setFpMailContent((String)param.get(Dict.mail_content));
			messageMailDTO.setFpMailTitle((String)param.get(Dict.mail_subject));
			messageMailDTO.setFpMailType(Dict.mail_order_per);
			messageMailDTO.setFpMailSendType(Dict.message_type_now);
			messageMailDTO.setFpMailSendTimes(new Integer(0));
			messageMailDTO.setStatus(Dict.status_normal);
			messageMailDTO.setFpMailSendStatus(Dict.message_status_not_send);
			messageMailDTO.setCreateBy(messageDTO.getUpdateBy());
			messageMailDTO.setUpdateBy(messageDTO.getUpdateBy());
			messageMailDTO.setCreateDate(messageDTO.getUpdateDate());
			messageMailDTO.setUpdateDate(messageDTO.getUpdateDate());
			
			String[] mailAddr = StringUtil.preEmailAddr(emailAddress);
			if(mailAddr!=null){
				for(String addr : mailAddr){
					messageMailDTO.setFpMailTo(addr);
					messageMailDaoImpl.addMessageMail(messageMailDTO);
				}
			}
		}
	}
}
